package com.rljk.common.interceptor;

import com.rljk.common.result.CodeMsg;
import com.rljk.domain.common.PageData;
import com.rljk.exception.GlobalException;
import com.rljk.redis.RedisService;
import com.rljk.service.UserManager;
import com.rljk.utils.Tools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Author:   YASUO
 * Date:     2018/7/18 11:30
 * Description:
 */
@Slf4j
//@Component
public class AppLoginInterceptor implements HandlerInterceptor {

    @Resource(name = "userService")
    private UserManager userService;

    @Autowired
    RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("=====拦截器开始拦截=======");
        String token = request.getParameter("TOKEN");
        log.info("token:"+token);
        String token1 = request.getParameter("USER_ID");
        log.info("token1:"+token1);
        if(Tools.isEmpty(token)){
            throw new GlobalException(CodeMsg.TOKEN_ERROR);
        }

        //1.获取用户信息
        String USER_ID = redisService.get(token);
        PageData pd = new PageData();
        pd.put("USER_ID",USER_ID);
        PageData user = userService.findById(pd);
        if(user==null){
            throw new GlobalException(CodeMsg.TOKEN_ERROR);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
